import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * Created with IntelliJ IDEA.
 * User: ttq
 * Date: 13-7-5
 * Time: 上午11:44
 * To change this template use File | Settings | File Templates.
 */
public class PriviledgeFilter implements Filter {
    private Properties properties = new Properties();

    public void init(FilterConfig config) throws ServletException {
        String file = config.getInitParameter("file");
        String realPath = config.getServletContext().getRealPath(file);

        try {
            properties.load(new FileInputStream(realPath));
        } catch (Exception e) {
            config.getServletContext().log("读取权限控制文件失败", e);
        }
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request1 = (HttpServletRequest) request;
        String requestURI = request1.getRequestURI().replace(request1.getContextPath() + "/", "");
        String action = request.getParameter("action");
        action = action == null ? "" : action;
        String uri = requestURI + "?action=" + action;
        String role = (String) request1.getSession(true).getAttribute("role");
        role = role == null ? "guest" : role;
        boolean authentificated = false;
        for (Object obj : properties.keySet()) {
            String key = ((String) obj);
            if (uri.matches(key.replace("?", "\\?").replace(".", "\\.").replace("*", ".*"))) {
                if (role.equals(properties.get(key))) {
                    authentificated = true;
                    break;
                }
            }
        }

        if (!authentificated) {
//            throw  new RuntimeException(new )
        }
        chain.doFilter(request, response);
    }

    public void destroy() {
        properties = null;
    }
}
